package com.google.wave.robot.scrimborg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.log4j.Logger;

public class ScrimFetcher {

	private static final Logger log = Logger.getLogger(ScrimFetcher.class.getSimpleName( ) );
	
	private static final String url = "http://scr.im/xml/";
	
	
	/**
	 * Response Format:
	 * <?xml version="1.0" encoding="UTF-8"?>
	 * 		<scrim>
	 *			<result>Success</result>
	 *			<email>c.akalugwu@gmail.com</email>
	 *			<scrim>1ywz</scrim>
	 *			<url>http://scr.im/1ywz</url>
	 *		</scrim>
	 * 
	 * @author: Charles Akalugwu
	 */
	public static String fetchScrim(String email) {
		
		StringBuilder scrimUrl = new StringBuilder();

		try {
			
			String data = URLEncoder.encode( "email", "UTF-8" ) + "=" + URLEncoder.encode( email, "UTF-8" );
			
			URL posturl = new URL( url );
			
			URLConnection conn = posturl.openConnection( );
            
            conn.setDoOutput(true);
            
            OutputStreamWriter writer = new OutputStreamWriter( conn.getOutputStream ( ) );
            
            writer.write( data );
            writer.flush( );
            writer.close( );
            
            BufferedReader reader = new BufferedReader( new InputStreamReader ( conn.getInputStream ( ) ) );
            String line;
         	
            while ( ( line = reader.readLine( ) ) != null ) {
            	
            	line = line.trim();
            	
            	if(  line.startsWith( "<result>" ) && !line.contains( "Success" )  ){
            		break;
            	}
            	
            	if( line.startsWith( "<url>" ) ){
					scrimUrl.append( line.substring( 5 , line.lastIndexOf( "<" ) ) );
					break;
				}
            }
            
            reader.close();

		} catch (MalformedURLException e) {
			log.error("malformed url exception: " + url + " msg:" + e.getMessage());
		} catch (IOException e) {
			log.error("io exception!url: " + url + " msg:" + e.getMessage());
		}
		
		log.debug( "returning "+ scrimUrl.toString( ) );
		
		return scrimUrl.toString();
	}

}
